﻿using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Flurl;
using Flurl.Http;
using Flurl.Util;
using System.Net.Http;
using System.Collections.Specialized;

namespace Pay.Service {
    public class ProductActivityService : ServiceBase, IProductActivityService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        private IActivityService _iActivityService;
        public ProductActivityService(IUnitOfWork iUnitOfWork, IActivityService iActivityService) : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
            _iActivityService = iActivityService;
        }

        #region 公共方法
        /// <summary>
        /// 获得活动产品分页列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedResult<product_dto> Gets(ProductActivityQuery query) {
            var filter = PredicateBuilder.True<ProductActivity>();
            filter = filter.And(c => c.Product.SaleStatus == SaleStatus.Sell && c.Product.AuditStatus != AuditStatus.Illegal);

            if (query.activityId > 0) {
                filter = filter.And(c => c.ActivityId == query.activityId);
            } else if (query.ActivityType == EActivityType.ProductOnlyRedDrill) {
                filter = filter.And(c => c.Activity.Type == query.ActivityType && 
                                    ((c.Activity.PreheatTime != null && c.Activity.PreheatTime <= query.Time) || c.Activity.BeginTime <= query.Time) && c.Activity.EndTime >= query.Time);
            } else {
                filter = filter.And(c => c.Activity.Type == query.ActivityType && c.Activity.BeginTime <= query.Time && c.Activity.EndTime >= query.Time);
            }

            if (query.merchant_id > 0)
                filter = filter.And(c => c.Product.Merchant.OemId == query.merchant_id || c.Product.MerchantId == query.merchant_id);
            if (query.sell_out.HasValue) {
                if (query.sell_out.Value)
                    filter = filter.And(c => c.Product.Stock == 0);
                else
                    filter = filter.And(c => c.Product.Stock > 0);
            }
            var q = context.ProductActivity.Where(filter).ToList().Distinct(new ProductActivityComParer());
            var list = new List<product_activity_dto>();
            if (query.ActivityType == EActivityType.ProductOnlyRedDrill) {
                list = q.OrderBy(c=> c.Activity.BeginTime).ThenByDescending(c => c.Top).ThenByDescending(o => o.Product.Top).Skip((query.page - 1) * query.size).Take(query.size).ToList().ToDtoList<product_activity_dto>() ?? new List<product_activity_dto>();
            } else {
                list = q.OrderByDescending(c => c.Top).ThenByDescending(o => o.Product.Top).Skip((query.page - 1) * query.size).Take(query.size).ToList().ToDtoList<product_activity_dto>() ?? new List<product_activity_dto>();
            }
            var rows = list.Select(o => o.product).ToList();
            if (rows != null && rows.Count() > 0) {
                for (var i = 0; i < rows.Count(); i++) {
                    var product_activity = list.Where(o => o.product_id == rows[i].id).FirstOrDefault();//可包含未开始的情况
                    rows[i] = ProductActivityHandle(rows[i], product_activity);
                }
            }
            var result = new PagedResult<product_dto>(rows, q.Count(), query.page, query.size);
            return result;
        }

        public class ProductActivityComParer : IEqualityComparer<ProductActivity> {
            public bool Equals(ProductActivity x, ProductActivity y) {
                return x.ProductId == y.ProductId;
            }
            public int GetHashCode(ProductActivity obj) {
                return obj.ToString().GetHashCode();
            }
        }

        /// <summary>
        /// 根据产品Id 获取当前是否参与活动
        /// </summary>
        /// <param name="product_id"></param>
        /// <returns></returns>
        public product_activity_dto GetAvailable(long product_id, long sku_id = 0) {
            var time = DateTime.Now;
            List<product_activity_dto> list = GetCacheList(product_id) ?? new List<product_activity_dto>();
            var q = list.Where(o => o.product_id == product_id && o.activity.begin_time <= time && o.activity.end_time >= time);
            if (sku_id > 0) {
                q = q.Where(o => o.product_sku_id == sku_id);
            }
            var result = q.FirstOrDefault().ToDtoObject<product_activity_dto>();
            return result;
        }

        /// <summary>
        /// 根据产品Id 获得正在进行中或者预热中的活动
        /// </summary>
        /// <param name="product_id"></param>
        /// <returns></returns>
        public product_activity_dto GetAvailableOrPreheat(long product_id, long sku_id = 0) {
            var time = DateTime.Now;
            List<product_activity_dto> list = GetCacheList(product_id) ?? new List<product_activity_dto>();
            var q = list.Where(o => o.product_id == product_id && ((o.activity.preheat_time != null && o.activity.preheat_time <= time)
                            || o.activity.begin_time <= time) && o.activity.end_time >= time);
            if (sku_id > 0) {
                q = q.Where(o => o.product_sku_id == sku_id);
            }
            var result = q.FirstOrDefault().ToDtoObject<product_activity_dto>();
            return result;
        }

        /// <summary>
        /// 根据产品Id 获得活动缓存列表（排除已结束的活动，已结束的活动产品不加入缓存，避免缓存过大。缓存取出后仍要判断结束时间，避免缓存导致结束不及时）
        /// </summary>
        /// <param name="product_id"></param>
        /// <returns></returns>
        public List<product_activity_dto> GetCacheList(long product_id) {
            return context.ProductActivity.Where(c => c.ProductId == product_id).FromCache(o =>
            {
                var timeNow = DateTime.Now;
                var result = o.Where(c => c.Activity.EndTime > timeNow).ToDtoList<product_activity_dto>();
                return result;
            }, "ProductActivity" + product_id);
        }

        /// <summary>
        /// 产品活动处理
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="isIncludePreHeat">是否包含预热</param>
        /// <param name="isOnlyCashPay">仅使用现金支付</param>
        /// <returns></returns>
        public product_dto ProductActivityHandle(product_dto dto, bool isIncludePreHeat = false, bool isOnlyCashPay = false) {
            var product_activity = new product_activity_dto();
            if (isIncludePreHeat == true)
                product_activity = GetAvailableOrPreheat(dto.id);

            else
                product_activity = GetAvailable(dto.id);
            return ProductActivityHandle(dto, product_activity, isOnlyCashPay);
        }

        /// <summary>
        /// 产品活动处理
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="product_activity"></param>
        /// <param name="isOnlyCashPay">仅使用现金支付</param>
        /// <returns></returns>
        private product_dto ProductActivityHandle(product_dto dto, product_activity_dto product_activity, bool isOnlyCashPay = false) {
            if (product_activity != null) {
                decimal raw_price = dto.price;
                decimal raw_cost_price = dto.cost_price ?? 0;
                dto.activity_ex = new product_dto_activity_ex();
                dto.price = product_activity.activity_price;
                dto.activity_ex.is_activity = true;
                dto.activity_ex.product_activity_id = product_activity.id;
                dto.activity_ex.activity_type = product_activity.activity.type;
                dto.activity_ex.begin_time = product_activity.activity.begin_time;
                dto.activity_ex.end_time = product_activity.activity.end_time;
                dto.activity_ex.preheat_time = product_activity.activity.preheat_time;
                if (product_activity.activity.type == EActivityType.ProductTimeBuy || product_activity.activity.type == EActivityType.ProductCashRedDrill ||
                    product_activity.activity.type == EActivityType.ProductOnlyRedDrill) {

                    if (product_activity.activity.type == EActivityType.ProductTimeBuy) {//限时购
                        dto.price = product_activity.activity_price * product_activity.product_activity_time_buy.min_buy_mum;
                        dto.cost_price = product_activity.product_activity_time_buy.cost_price * product_activity.product_activity_time_buy.min_buy_mum;
                    }else if(product_activity.activity.type == EActivityType.ProductCashRedDrill && isOnlyCashPay == false) {//红钻+现金活动 并且使用红钻+现金方式支付
                        dto.price = product_activity.activity_price * product_activity.product_activity_time_buy.min_buy_mum;
                        dto.cost_price = product_activity.product_activity_time_buy.cost_price * product_activity.product_activity_time_buy.min_buy_mum;
                        dto.activity_ex.activity_red_drill = product_activity.activity_red_drill * product_activity.product_activity_time_buy.min_buy_mum;
                    }else if(product_activity.activity.type == EActivityType.ProductCashRedDrill && isOnlyCashPay == true) {//红钻+现金活动 并且使用纯现金方式支付  取商品原价和成本价
                        dto.price = raw_price * product_activity.product_activity_time_buy.min_buy_mum;
                        dto.cost_price = raw_cost_price * product_activity.product_activity_time_buy.min_buy_mum;
                    }else if(product_activity.activity.type == EActivityType.ProductOnlyRedDrill) {//红钻兑换 只有红钻部分 销售价，结算价为0
                        dto.activity_ex.activity_red_drill = product_activity.activity_red_drill * product_activity.product_activity_time_buy.min_buy_mum;
                        dto.price = 0;
                        dto.cost_price = 0;
                    }


                    dto.distribution_price = ((decimal)(dto.price - dto.cost_price) * GetDistributionRate(dto.path)).NumberToFixedNoRound(2); //Math.Round((decimal)((dto.price - dto.cost_price) * GetDistributionRate(dto.path)), 2, MidpointRounding.AwayFromZero);
                    dto.market_price = dto.market_price * product_activity.product_activity_time_buy.min_buy_mum;
                    dto.max_quantity = product_activity.product_activity_time_buy.max_buy_num;
                    dto.activity_ex.is_sold_out = product_activity.is_sold_out;
                    dto.stock = product_activity.is_sold_out ? 0 : product_activity.activity_stock;

                    if (dto.product_skus != null && dto.product_skus.Count() > 0) {//产品有规格，取价格最低的价格作为产品价格
                        for (var i = 0; i < dto.product_skus.Count(); i++)
                            dto.product_skus[i] = SkuActivityHandle(dto.product_skus[i], DateTime.Now < product_activity.activity.begin_time ? true : false, isOnlyCashPay);//更新商品规格的活动价

                        var minSku = dto.product_skus.OrderBy(o => o.price).FirstOrDefault();//取活动价最低的规格，作为商品相关价格

                        dto.price = minSku.price;
                        dto.activity_ex.activity_red_drill = minSku.activity_ex != null ? dto.activity_ex.activity_red_drill : 0;
                        dto.max_quantity = minSku.max_quantity;
                        dto.cost_price = minSku.cost_price;
                        dto.distribution_price = minSku.distribution_price;
                        dto.activity_ex.is_sold_out = dto.product_skus.Exists(o => o.activity_ex != null && o.activity_ex.is_sold_out == false) ? false : true;//所有规格售罄，商品才售罄
                        dto.stock = dto.activity_ex.is_sold_out ? 0 : dto.product_skus.Sum(o => o.stock);
                    }

                } else if (product_activity.activity.type == EActivityType.ProductMaker) {
                    dto.cost_price = product_activity.product_token_maker.cost_price;
                    dto.distribution_price = product_activity.product_token_maker.distribution_price;
                }
                if (dto.product_skus != null && dto.product_skus.Count() > 0) {
                    for (var i = 0; i < dto.product_skus.Count(); i++) {
                        dto.product_skus[i] = SkuActivityHandle(dto.product_skus[i], DateTime.Now < product_activity.activity.begin_time ? true : false, isOnlyCashPay);
                    }
                }
            }


            return dto;
        }

        /// <summary>
        /// 产品规格活动处理
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="isIncludePreHeat"></param>
        /// <param name="isOnlyCashPay"></param>
        /// <returns></returns>
        public product_sku_dto SkuActivityHandle(product_sku_dto dto, bool isIncludePreHeat = false, bool isOnlyCashPay = false) {
            var product_activity = new product_activity_dto();
            if (isIncludePreHeat == true)
                product_activity = GetAvailableOrPreheat(dto.product_id, dto.id);

            else
                product_activity = GetAvailable(dto.product_id, dto.id);

            return SkuActivityHandle(dto, product_activity, isOnlyCashPay);

        }

        /// <summary>
        /// 产品规格活动处理
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="product_activity"></param>
        /// <param name="isOnlyCashPay">仅使用现金支付</param>
        /// <returns></returns>
        private product_sku_dto SkuActivityHandle(product_sku_dto dto, product_activity_dto product_activity, bool isOnlyCashPay = false) {
            if (product_activity != null) {
                decimal raw_price = dto.price;
                decimal raw_cost_price = dto.cost_price;
                dto.activity_ex = new product_dto_activity_ex();
                dto.price = product_activity.activity_price;
                dto.activity_ex.is_activity = true;
                dto.activity_ex.product_activity_id = product_activity.id;
                dto.activity_ex.activity_type = product_activity.activity.type;
                dto.activity_ex.begin_time = product_activity.activity.begin_time;
                dto.activity_ex.end_time = product_activity.activity.end_time;
                dto.activity_ex.preheat_time = product_activity.activity.preheat_time;
                if (product_activity.activity.type == EActivityType.ProductTimeBuy || product_activity.activity.type == EActivityType.ProductCashRedDrill ||
                    product_activity.activity.type == EActivityType.ProductOnlyRedDrill) {

                    if (product_activity.activity.type == EActivityType.ProductTimeBuy) {//限时购
                        dto.price = product_activity.activity_price * product_activity.product_activity_time_buy.min_buy_mum;
                        dto.cost_price = product_activity.product_activity_time_buy.cost_price * product_activity.product_activity_time_buy.min_buy_mum;
                    } else if (product_activity.activity.type == EActivityType.ProductCashRedDrill && isOnlyCashPay == false) {//红钻+现金活动 并且使用红钻+现金方式支付
                        dto.price = product_activity.activity_price * product_activity.product_activity_time_buy.min_buy_mum;
                        dto.cost_price = product_activity.product_activity_time_buy.cost_price * product_activity.product_activity_time_buy.min_buy_mum;
                        dto.activity_ex.activity_red_drill = product_activity.activity_red_drill * product_activity.product_activity_time_buy.min_buy_mum;
                    } else if (product_activity.activity.type == EActivityType.ProductCashRedDrill && isOnlyCashPay == true) {//红钻+现金活动 并且使用纯现金方式支付  取商品原价和成本价
                        dto.price = raw_price * product_activity.product_activity_time_buy.min_buy_mum;
                        dto.cost_price = raw_cost_price * product_activity.product_activity_time_buy.min_buy_mum;
                    } else if (product_activity.activity.type == EActivityType.ProductOnlyRedDrill) {//红钻兑换 只有红钻部分 销售价，结算价为0
                        dto.activity_ex.activity_red_drill = product_activity.activity_red_drill * product_activity.product_activity_time_buy.min_buy_mum;
                        dto.price = 0;
                        dto.cost_price = 0;
                    }

                    var product = context.Products.FindById(dto.product_id);
                    dto.distribution_price = ((decimal)(dto.price - dto.cost_price) * GetDistributionRate(product != null ? product.Path : "")).NumberToFixedNoRound(2); //Math.Round((decimal)((dto.price - dto.cost_price) * GetDistributionRate(dto.path)), 2, MidpointRounding.AwayFromZero);

                    dto.max_quantity = product_activity.product_activity_time_buy.max_buy_num;
                    dto.activity_ex.is_sold_out = product_activity.is_sold_out;
                    dto.stock = product_activity.is_sold_out ? 0 : product_activity.activity_stock;
                } else if (product_activity.activity.type == EActivityType.ProductMaker) {
                    dto.cost_price = product_activity.product_token_maker.cost_price;
                    dto.distribution_price = product_activity.product_token_maker.distribution_price;
                }
            }

            return dto;
        }
        #endregion

        /// <summary>
        /// 获得分销比例
        /// </summary>
        /// <param name="productPath"></param>
        /// <returns></returns>
        private decimal GetDistributionRate(string productPath) {
            decimal distribution_rate = 1;
            try {
                if (!string.IsNullOrEmpty(productPath)) {
                    distribution_rate = decimal.Parse(productPath);
                    if (distribution_rate < 0 || distribution_rate > 1)
                        distribution_rate = 1;
                }
            }
            catch {
                return 1;
            }
            return distribution_rate;
        }
        #region 限时购
        /// <summary>
        /// 获得活动对应的限时购数据（用于编辑）
        /// </summary>
        /// <param name="activityId"></param>
        /// <returns></returns>
        public List<product_activity_time_buy_edit_model> GetProductTimeBuyEdit(long activityId) {
            var results = new List<product_activity_time_buy_edit_model>();
            var productActivityList = context.ProductActivity.Where(o => o.ActivityId == activityId).OrderByDescending(o => o.Top).ToDtoList<product_activity_dto>();
            if (productActivityList != null && productActivityList.Count() > 0) {
                foreach (var pa in productActivityList) {
                    var model = new product_activity_time_buy_edit_model() {
                        activity_id = pa.activity_id,
                        product_activity_id = pa.id,
                        product_id = pa.product_id,
                        product_sku_id = pa.product_sku_id,
                        product_name = pa.product.name,
                        product_sku_name = pa.product_sku == null ? "" : pa.product_sku.sku_name,
                        product_price = pa.product_sku != null ? pa.product_sku.price : pa.product.price,
                        activity_price = pa.activity_price,
                        activity_red_drill = pa.activity_red_drill,
                        activity_stock = pa.activity_stock,
                        raw_cost_price = pa.product_sku != null ? pa.product_sku.cost_price : pa.product.cost_price ?? 0,
                        cost_price = pa.product_activity_time_buy.cost_price,
                        min_buy_mum = pa.product_activity_time_buy.min_buy_mum,
                        max_buy_num = pa.product_activity_time_buy.max_buy_num,
                        horse_power = pa.product_activity_time_buy.horse_power,
                        horse_power_effective = pa.product_activity_time_buy.horse_power_effective,
                        is_sold_out = pa.is_sold_out,
                        sale_count = pa.sale_count,
                        top = pa.top,
                        distribution_rate = GetDistributionRate(pa.product.path),
                    };

                    results.Add(model);
                }
            }

            return results;
        }
        /// <summary>
        /// 新增或修改限时购
        /// </summary>
        /// <param name="editModel"></param>
        /// <returns></returns>
        public bool AddOrUpdateProductTimeBuy(product_activity_time_buy_edit editModel) {
            List<string> cacheList = new List<string>();
            var list = editModel.list;
            if (list == null)
                list = new List<product_activity_time_buy_edit_model>();
            using (var trans = context.Database.BeginTransaction()) {
                try {
                    var activity = _iActivityService.GetActivity(editModel.activity.id);
                    #region 活动未开始，允许删除已添加的商品  一定要先于添加操作
                    //活动未开始，允许删除已添加的商品
                    List<long> removeProductActivityIds = new List<long>();
                    List<long> pageProductActivityIds = list.Where(o => o.product_activity_id > 0).Select(o => o.product_activity_id).ToList() ?? new List<long>();//页面上的活动产品Id
                    List<long> dataProductActivityIds = context.ProductActivity.Where(o => o.ActivityId == activity.id).Select(o => o.Id).ToList() ?? new List<long>(); // 数据库中的活动产品Id
                    foreach (var id in dataProductActivityIds) {
                        if (!pageProductActivityIds.Exists(o => o == id))// id 存在于数据库中  不存在于页面上，说明要删除
                            removeProductActivityIds.Add(id);
                    }
                    if (removeProductActivityIds != null && removeProductActivityIds.Count() > 0) {
                        if (activity.begin_time <= DateTime.Now)
                            throw new ServerErrorException("只有未开始的活动，才允许删除商品");

                        foreach (var removeProductActivityId in removeProductActivityIds) {
                            var rm1 = context.ProductActivityTimeBuy.Where(o => o.ProductActivityId == removeProductActivityId).FirstOrDefault();
                            var rm2 = context.ProductActivity.FindById(removeProductActivityId);
                            context.ProductActivityTimeBuy.Remove(rm1);
                            context.ProductActivity.Remove(rm2);
                            cacheList.Add("ProductActivity" + rm2.ProductId);
                        }

                    }
                    #endregion

                    if (list != null && list.Count() > 0) {
                        var temp = (from q in list
                                    group q by new { q.product_id, q.product_sku_id } into g
                                    where g.Count() > 1
                                    let t = g
                                    from s in t
                                    select s).ToList();
                        if (temp != null && temp.Count() > 0)
                            throw new ServerErrorException(string.Format("不允许重复添加同一款商品，商品：{0}， 规格：{1}", temp.FirstOrDefault().product_name, temp.FirstOrDefault().product_sku_name));

                        foreach (var item in list) {
                            cacheList.Add("ProductActivity" + item.product_id + "_" + item.product_sku_id);
                            cacheList.Add("ProductActivity" + item.product_id);
                            if (activity.type != EActivityType.ProductOnlyRedDrill) {
                                if (item.cost_price <= 0)
                                    throw new ServerErrorException(string.Format("商品：{0}，规格：{1}，结算价格必须大于0", item.product_name, item.product_sku_name));
                                if (item.activity_price < item.cost_price)
                                    throw new ServerErrorException(string.Format("商品：{0}，规格：{1} 活动价格(￥{2})不能小于 结算价(￥{3})",
                                                                   item.product_name, item.product_sku_name, item.activity_price, item.cost_price));
                            } else {//红钻兑换
                                if (item.activity_red_drill <= 0)
                                    throw new ServerErrorException(string.Format("红钻兑换类型活动，商品：{0}，规格：{1}，活动价（红钻）必须大于0", item.product_name, item.product_sku_name));
                                item.cost_price = 0;
                                item.activity_price = 0;
                            }

                            if(item.activity_red_drill < 0)
                                throw new ServerErrorException(string.Format("红钻兑换类型活动，商品：{0}，规格：{1}，活动价（红钻）不能小于0", item.product_name, item.product_sku_name));

                            if (item.product_sku_id > 0) {//有规格
                                var sku = context.ProductSkus.FindById(item.product_sku_id).ToDtoObject<product_sku_dto>();
                                if (item.activity_stock > sku.stock && item.is_sold_out == false)
                                    throw new ServerErrorException(string.Format("商品：{0}，规格：{1}，活动库存不能大于该规格库存", item.product_name, item.product_sku_name));
                                if (item.activity_stock == 0)
                                    item.is_sold_out = true;
                                if (item.activity_stock < 0)
                                    throw new ServerErrorException(string.Format("商品：{0}，规格：{1}，活动库存不能小于0", item.product_name, item.product_sku_name));
                            } else {//无规格
                                var product = context.Products.FindById(item.product_id).ToDtoObject<product_dto>();
                                if (item.activity_stock > product.stock && item.is_sold_out == false)
                                    throw new ServerErrorException(string.Format("商品：{0}，活动库存不能大于该规格库存", item.product_name));
                                if (item.activity_stock == 0)
                                    item.is_sold_out = true;
                                if (item.activity_stock < 0)
                                    throw new ServerErrorException(string.Format("商品：{0}，活动库存不能小于0", item.product_name));
                            }
                            if (item.product_activity_id == 0) {//新增
                                if (context.ProductActivity.Exist(o => o.ActivityId == activity.id && o.ProductId == item.product_id && o.ProductSkuId == item.product_sku_id))//该活动已添加过该款商品
                                    throw new ServerErrorException("页面数据已过期，请先刷新");
                                var timeNow = DateTime.Now;
                                var vaidtemp = context.ProductActivity.Where(o => o.ActivityId != activity.id && o.ProductId == item.product_id && o.Activity.EndTime >= timeNow
                                             && ((activity.begin_time <= o.Activity.BeginTime && activity.end_time >= o.Activity.BeginTime) || (activity.begin_time <= o.Activity.BeginTime && activity.end_time >= o.Activity.EndTime)
                                             || (activity.begin_time >= o.Activity.BeginTime && activity.end_time <= o.Activity.EndTime) || (activity.begin_time <= o.Activity.EndTime && activity.end_time >= o.Activity.EndTime))).FirstOrDefault();
                                if (vaidtemp != null)
                                    throw new ServerErrorException(string.Format("商品：{0} 已存在于其他同一时段的活动中", vaidtemp.Product.Name));
                                //再次检查预开始时间-结束时间
                                vaidtemp = context.ProductActivity.Where(o => o.ActivityId != activity.id && o.ProductId == item.product_id && o.Activity.EndTime >= timeNow
                                             && ((activity.preheat_time <= o.Activity.PreheatTime && activity.end_time >= o.Activity.PreheatTime) || (activity.preheat_time <= o.Activity.PreheatTime && activity.end_time >= o.Activity.EndTime)
                                             || (activity.preheat_time >= o.Activity.PreheatTime && activity.end_time <= o.Activity.EndTime) || (activity.preheat_time <= o.Activity.EndTime && activity.end_time >= o.Activity.EndTime))).FirstOrDefault();
                                if (vaidtemp != null)
                                    throw new ServerErrorException(string.Format("商品：{0} 已存在于其他同一时段的活动中", vaidtemp.Product.Name));
                                vaidtemp = context.ProductActivity.Where(o => o.Activity.Type == EActivityType.ProductMaker && o.ProductId == item.product_id).FirstOrDefault();
                                if (vaidtemp != null)
                                    throw new ServerErrorException(string.Format("商品：{0}，已存在于“创客商品”活动中", vaidtemp.Product.Name));

                                var productActivity = new ProductActivity() {
                                    ProductId = item.product_id,
                                    ProductSkuId = item.product_sku_id,
                                    ActivityId = item.activity_id,
                                    ActivityPrice = item.activity_price,
                                    ActivityStock = item.activity_stock,
                                    ActivityRedDrill = item.activity_red_drill,
                                    IsSoldOut = item.activity_stock == 0 ? true : false,
                                    Top = item.top,
                                    CreateTime = DateTime.Now.ToUnix()
                                };
                                context.ProductActivity.Add(productActivity);
                                _iUnitOfWork.Commit();//提交用于获得自增Id
                                var productTimeBuy = new ProductActivityTimeBuy() {
                                    ProductActivityId = productActivity.Id,
                                    CostPrice = item.cost_price,
                                    MinBuyNum = item.min_buy_mum,
                                    MaxBuyNum = item.max_buy_num,
                                    HorsePower = item.horse_power,
                                    HorsePowerEffective = item.horse_power_effective

                                };
                                context.ProductActivityTimeBuy.Add(productTimeBuy);

                            } else {//修改
                                var productActivity = context.ProductActivity.FindById(item.product_activity_id);
                                productActivity.ActivityPrice = item.activity_price;
                                productActivity.ActivityRedDrill = item.activity_red_drill;
                                productActivity.IsSoldOut = item.is_sold_out;
                                productActivity.ActivityStock = item.activity_stock;
                                productActivity.Top = item.top;
                                productActivity.ProductActivityTimeBuy.CostPrice = item.cost_price;
                                productActivity.ProductActivityTimeBuy.MinBuyNum = item.min_buy_mum;
                                productActivity.ProductActivityTimeBuy.MaxBuyNum = item.max_buy_num;
                                productActivity.ProductActivityTimeBuy.HorsePower = item.horse_power;
                                productActivity.ProductActivityTimeBuy.HorsePowerEffective = item.horse_power_effective;
                            }
                        }
                    }



                    var result = _iUnitOfWork.Commit(cacheList.ToArray()) > 0;
                    trans.Commit();
                    return result;
                }
                catch (ServerErrorException ex) {
                    trans.Rollback();
                    throw ex;
                }
                catch (Exception ex) {
                    trans.Rollback();
                    throw ex;
                }
            }

        }

        #endregion
    }
}
